<?php
//error_reporting(0);
session_start(); // 启用会话
require_once BASE_PATH.'/db/database.php';

class Comments extends Database
{
    public function getNoteComments($note_id, $page = 1, $limit = 12) {

        if (!isUid($note_id)) {
            return json_encode(['status' => '201', 'message' => '无效note_id']);
        }
        $offset = ($page - 1) * $limit;

        // 获取评论内容
        $sql = "SELECT c.*, u.avatar, u.nickname 
                FROM comments c 
                LEFT JOIN user u ON c.user_id = u.user_id 
                WHERE c.note_id = '{$note_id}' 
                ORDER BY c.comments_time DESC 
                LIMIT {$offset}, {$limit}";

        //return $this->getAll($sql);


        $comments = json_decode($this->getAll($sql),true);


        foreach ($comments as &$comment) {
            // 假设 publish_ip 是以整数形式存储的 IP 地址
            $comment['iparea'] = getIpProvince($comment['publish_ip']); // 获取 IP 区域
            $comment['formattime'] = formatNoteTime($comment['comments_time']); // 格式化时间
        }

        return json_encode($comments);

    }

    public function getNotifyComments($note_user_id, $page = 1, $limit = 12) {

        if (!isUid($note_user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $offset = ($page - 1) * $limit;

        // 查询评论表，并联结用户表和笔记表获取相关信息
        /*
         * SELECT c.*, u.avatar, u.nickname, n.title, n.content as ncontent
            FROM comments c
            LEFT JOIN note n ON c.note_id = n.note_id
            LEFT JOIN user u ON c.user_id = u.user_id
            WHERE c.note_user_id = '002c99d735d2f472d5f307d8'
            ORDER BY c.comments_time DESC
            LIMIT 12 OFFSET 1;

         */
        $sql = "SELECT c.*, u.avatar, u.nickname, n.title, n.content as ncontent, n.image
            FROM comments c
            LEFT JOIN note n ON c.note_id = n.note_id
            LEFT JOIN user u ON c.user_id = u.user_id
            WHERE c.note_user_id = '{$note_user_id}'
            ORDER BY c.comments_time DESC
            LIMIT $limit OFFSET $offset;";

        $comments = $this->getAll($sql);

        return $comments;
    }

    public function getNotifyCommentsTotal($note_user_id, $limit = 12) {

        if (!isUid($note_user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $countSql = "SELECT COUNT(*) as total
            FROM comments c
            LEFT JOIN note n ON c.note_id = n.note_id
            LEFT JOIN user u ON c.user_id = u.user_id
            WHERE c.note_user_id = '{$note_user_id}'
            LIMIT $limit;";


        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $limit); // 计算总页码

        return $comments;
    }

    public function getUserComments($user_id, $page = 1, $limit = 12) {

        if (!isUid($user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }

        $offset = ($page - 1) * $limit;

        $sql = "SELECT c.*, u.avatar, u.nickname, n.title, n.content as ncontent, n.image
            FROM comments c
            LEFT JOIN note n ON c.note_id = n.note_id
            LEFT JOIN user u ON c.user_id = u.user_id
            WHERE c.user_id = '{$user_id}'
            ORDER BY c.comments_time DESC
            LIMIT $limit OFFSET $offset;";

        $comments = $this->getAll($sql);

        return $comments;
    }

    public function getUCommentsTotalPage($user_id, $limit = 12) {

        if (!isUid($user_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid']);
        }


        $countSql = "SELECT COUNT(*) as total
            FROM comments c
            WHERE c.user_id = '{$user_id}'
            ";

        $countResult = json_decode($this->getRow($countSql),true);
        $totalCount = $countResult ? $countResult['total'] : 0; // 获取总记录数
        return ceil($totalCount / $limit); // 计算总页码
    }

    public function UserdeleteComments($uid,$cid) {

        if (!isUid($uid)||!isUid($cid)) {
            return json_encode(['status' => '201', 'message' => '无效uid/cid']);
        }

        $sql = "DELETE FROM `comments` WHERE `comments_id` = '{$cid}' and `user_id` = '{$uid}'";

        $res = $this->query($sql);
        if ($res){
            return json_encode(['status' => '200', 'message' => '删除成功！']);
        }else{
            return json_encode(['status' => '201', 'message' => '不存在的评论！']);
        }
    }

    public function deleteComments($nid,$cid) {

        if (!isUid($nid)||!isUid($cid)) {
            return json_encode(['status' => '201', 'message' => '无效uid/cid']);
        }

        $sql = "DELETE FROM `comments` WHERE `comments_id` = '{$cid}' and `note_user_id` = '{$nid}'";

        $res = $this->query($sql);
        if ($res){
            return json_encode(['status' => '200', 'message' => '删除成功！']);
        }else{
            return json_encode(['status' => '201', 'message' => '不存在的评论！']);
        }
    }


    public function getAllComments($page = 1, $limit = 12) {
        $offset = ($page - 1) * $limit;

        // 获取满足条件的评论的总数
        $countSql = "SELECT COUNT(*) as total FROM comments";

        $total = json_decode($this->getRow($countSql),true)['total'];

        // 计算总页数
        $totalPages = ceil($total / $limit);


        $sql = "SELECT c.*, u.avatar, u.nickname, n.title 
            FROM comments c
            LEFT JOIN note n ON c.note_id = n.note_id
            LEFT JOIN user u ON c.user_id = u.user_id
            ORDER BY c.comments_time DESC
            LIMIT $limit OFFSET $offset;";

        $data = json_decode($this->getAll($sql), true);


        // 返回结果，包括评论数据、总页数和总记录数
        return [
            'totalPages' => $totalPages,
            'totalCount' => $total,
            'data' => $data,
        ];
    }

    public function sendComments($user_id, $note_id, $comment,$botIp=null) {
        if (!isUid($user_id) || !isUid($note_id)) {
            return json_encode(['status' => '201', 'message' => '无效uid/fans_id']);
        }
        $currentTimestamp = time();
        if($botIp){
            $uip_sql = "SELECT ip FROM `user` where user_id = '{$user_id}'";
            $user_ip = json_decode($this->getRow($uip_sql),true)['ip'];
            $ip = $user_ip;
            if(!$user_ip){
                $ip = random_chinese_ip();
            }

        }else{
            $ip = getUserIpAsLong();
        }
        $cid = generateCommentsId($user_id, $note_id);

        // 转义评论内容
        if (!isset($comment) || trim($comment) === '') {
            return json_encode(['status' => '201', 'message' => '禁止空评论！']);
        }

        $comment = addslashes($comment);
        $comment = htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
        $comment = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $comment);

        $nuid_sql = "SELECT user_id FROM `note` where note_id = '{$note_id}'";
        $note_user_id = json_decode($this->getRow($nuid_sql),true)['user_id'];

        $sql = "INSERT INTO comments (comments_id, user_id, note_id, note_user_id, content, publish_ip, comments_time) 
                VALUES ('{$cid}', '{$user_id}', '{$note_id}', '{$note_user_id}', '{$comment}', '{$ip}', {$currentTimestamp})";
        $res = $this->query($sql);
        if ($res){
            // 更新 note_statistics 表中的 comments_count
            $updateSql = "UPDATE note_statistics SET comments_count = comments_count + 1 WHERE note_id = '{$note_id}'";
            $this->query($updateSql);
            return json_encode(['status' => '200', 'message' => '发布评论成功！']);
        }else{
            return json_encode(['status' => '201', 'message' => '发布评论失败！']);
        }
    }

}
?>


